#include "server.h"

char ch1[20] = "Admin";
char ch2[10] = "123456";

sqlite3 * db = NULL;

pthread_mutex_t lock;

//将数据保存到userManage结构体中
int save_userInfo(int socket_fd, struct user * userInfo, struct userManage *puMge)
{
	printf ("数据保存中.....\n");
	//pthread_mutex_lock(&lock);
	int i = 0;
	for (i = 0; i < 20; i++)
	{
		if (uMge.flag[i] == 1)
		{
			continue;
		}
		printf ("数据写入缓存区.....\n");
		puMge->users[i].socketfd = socket_fd;
		strcpy(puMge->users[i].name, userInfo->name);
		strcpy(puMge->users[i].password, userInfo->password);
		uMge.flag[i] = 1;
		uMge.ban_flag[i] = 0;
		
		//转存到数据库中
		printf ("数据写入数据库.....\n");
		
		int result = sqlite3_open("server.db", &db);
		if (result != SQLITE_OK)
		{
			printf ("open server.db error!\n");
			return -1;
		}
		
		char buff[200];
		char *errmsg;
	
		sprintf (buff, "insert into register values('%s', '%s', '%d' ,'%d')", userInfo->name, userInfo->password, uMge.flag[i], uMge.ban_flag[i]);
		result = sqlite3_exec(db, buff, NULL, NULL, &errmsg);
		if (result != SQLITE_OK)
		{
			printf ("insert register table error : %d(%s)!\n", result, errmsg);
			printf ("数据保存失败！\n");
			return -1;
		} 
		else
		{
			printf ("数据保存成功！\n");
			return 1;
		}
		
		sqlite3_close(db);
		
		break;
	}
	//pthread_mutex_unlock(&lock);
	return 0;
}

int read_userInfo(struct userManage *puMge)
{
	printf ("读取数据库中数据.....\n");
	
	int result = sqlite3_open("server.db", &db);
	if (result != SQLITE_OK)
	{
		printf ("open server.db error!\n");
		return -1;
	}
	
	pthread_mutex_lock(&lock);
	char **resultp = NULL;
	char *errmsg;
	int nrow, ncolumn;
	int i = 0;
	
	printf ("读取表中数据.....\n");
	result = sqlite3_get_table(db, "select * from register", &resultp, &nrow, &ncolumn, &errmsg);
	if (result != SQLITE_OK)
	{
		printf ("select register table error : %d(%s)!\n", result, errmsg);
		return -1;
	}
		
	for (i = 0; i < nrow; i++)
	{
		if (resultp == NULL)         //空表
		{
			printf ("这是空表！\n");
			break;
		}
		
		char *pname;
		char *ppassword;
		char *pflag;
		char *pb_flag;
		int j;
		j = (i+1)*4;
		pname = resultp[j];
		ppassword = resultp[j+1];
		pflag = resultp[j+2];
		pb_flag = resultp[j+3];
		strcpy (puMge->users[i].name, pname);
		strcpy (puMge->users[i].password, ppassword);
		puMge->flag[i] = (int)(*pflag - '0');
		puMge->ban_flag[i] = (int)(*pb_flag - '0');
	}
	printf ("数据读取完毕！\n");
	printf ("\n");
	
	printf ("name\tpassword\tflag\tban_flag\n");
	for (i = 0; i < nrow; i++)
	{
		printf ("%s\t%s\t\t %d\t   %d\n", uMge.users[i].name, uMge.users[i].password, uMge.flag[i], uMge.ban_flag[i]);
	}
	printf ("\n");
	sqlite3_close(db);
	pthread_mutex_unlock(&lock);
}

int server_request(int cfd)
{	
	int readSize, writeSize;
	int ret = 0;
	struct user userInfo;
	int toname_fd = -1;
	int isRegister = -1;     //用户注册标志位，已注册为1，未注册为-1
	while (readSize = read(cfd, &userInfo, sizeof(userInfo)))
	{
		if (readSize == -1)
		{
			perror("read");
			return -1;
		} 
	
		switch (userInfo.cmd)
		{
			
			case REGISTER: //用户注册
			{
				printf ("收到一条消息\n");
				printf ("用户%s发送了注册命令:%d\n", userInfo.name,userInfo.cmd);
				printf ("用户名:%s\n", userInfo.name);
				printf ("密码:%s\n", userInfo.password);
				
				int i;
				//检测该用户名是否被注册
				printf("注册中.....\n");
				for (i = 0; i < 20; i++)       
				{
					if (uMge.flag[i] == 1)        
					{
						if (uMge.users[i].socketfd == cfd)
						{
							if (strcmp(uMge.users[i].name, userInfo.name) == 0)
							{
								isRegister = 1;              //若用户已注册，将isRegister置1
								printf ("该用户已注册，不能重复注册！\n"); 
								userInfo.result = REGISTER_REPEAT;
							}
						}
					}
				}
				
				if (isRegister != 1)
				{
					isRegister = -1;
					int save_flag = save_userInfo(cfd, &userInfo, &uMge);               // 将用户信息进行保存
					if (save_flag == 1)
					{
						printf ("用户 %s 注册成功！\n", userInfo.name);
						userInfo.result = REGISTER_SUCCESS;
					}
					
					else 
					{
						printf ("用户 %s 注册失败！\n", userInfo.name);
						userInfo.result = REGISTER_FAIL;
					}
					
				}
				
				writeSize = write(cfd, &userInfo, sizeof(userInfo));
				if (writeSize == -1)
				{
					perror("write");
					return -1;
				}
				
				memset(userInfo.name, 0, sizeof(userInfo.name));
				memset(userInfo.password, 0, sizeof(userInfo.password));
				memset(userInfo.npassword, 0, sizeof(userInfo.npassword));
				
					
				break;
			}
			
			case LOG_IN://用户登录
			{
				printf ("收到一条消息\n");
				printf ("用户%s发送了登录命令:%d\n", userInfo.name,userInfo.cmd);
				printf ("用户名:%s\n", userInfo.name);
				printf ("密码:%s\n", userInfo.password);
				int i;
				
				for (i = 0; i < 20; i++)
				{
					//检测该用户是否注册
					if (strcmp(uMge.users[i].name, userInfo.name) == 0)
					{
						isRegister = 1;    
						printf ("该用户已注册！\n"); 
						//检测该用户是否已登录
						if (uMge.online_flag[i] == 0)      //未登录
						{
							printf ("该用户未登录！\n"); 
							//检测该用户密码是否正确
							if (strcmp(uMge.users[i].password, userInfo.password) == 0)
							{
								printf ("密码正确！\n"); 
								uMge.online_flag[i] = 1;
								uMge.users[i].socketfd = cfd;
								printf ("在线标志位：%d\n", uMge.online_flag[i]);
								userInfo.result = LOGIN_SUCCESS;
								printf ("用户%s登录成功！\n", uMge.users[i].name);	
							}
						
							else
							{
								printf ("密码错误！\n"); 
								userInfo.result = PASSWORD_ERROR;
							}
						}	
						
						else
						{
							printf ("该用户已登录，不能重复登录！\n"); 
							userInfo.result = LOGIN_REPEAT;
						}
					}
					
				}
				
				if (isRegister != 1)
				{
					isRegister = -1;
					printf ("该用户未注册！\n"); 
					userInfo.result = NOT_REGISTER ;
				}
				
				writeSize = write(cfd, &userInfo, sizeof(userInfo));
				if (writeSize == -1)
				{
					perror("write");
					return -1;
				}
				
				memset(userInfo.name, 0, sizeof(userInfo.name));
				memset(userInfo.password, 0, sizeof(userInfo.password));
				
				
				break;
			}
			
			case CHAT_ONE://私聊
			{
				printf ("收到一条消息\n");
				printf ("用户%s发送了私聊命令:%d\n", userInfo.name,userInfo.cmd);
				
				pthread_mutex_lock(&lock);
				
				//建一个文本文件保存用户聊天记录
				char ch1[10] = {0};
				char ch2[10] = ".txt";
				char ch3[20] = {0};
				
				strcpy (ch1, userInfo.name);
				strcpy (ch3, userInfo.name);
				strcat (ch3, ch2);
				
				int fd_chat = open (ch3, O_RDWR | O_CREAT, S_IRUSR | S_IWUSR);
				if (-1 == fd_chat)
				{
					perror("open TXT");
					return -1;
				}
				
				close(fd_chat);
				
				int i;
				int temp = 0;
				for (i = 0; i < 20; i++)
				{
					//检测该用户是否注册
					if (strcmp(uMge.users[i].name, userInfo.name) == 0)
					{
						isRegister = 1;    
						printf ("该用户已注册！\n"); 
						
						//检测是否被禁言
						if (uMge.ban_flag[i] == 0)
						{
							temp = 0;
							printf ("禁言标志位：%d\n", uMge.ban_flag[i]);
							printf ("该用户允许发言！\n"); 
							//检测该用户是否已登录
							if (uMge.online_flag[i] == 1)      //已登录
							{
								printf ("在线标志位：%d\n", uMge.online_flag[i]);
								printf ("用户%s已登录！\n", uMge.users[i].name);
							}
							
							else
							{
								printf ("在线标志位：%d\n", uMge.online_flag[i]);
								printf ("该用户未登录！\n"); 
								userInfo.result = LOGIN_NULL;
							}
						}
						
						else
						{
							temp = 1;
							printf ("禁言标志位：%d\n", uMge.ban_flag[i]);
							printf ("该用户已被禁言！\n"); 
							userInfo.result = BAN_USER;
							
							break;
						}
					}
					
				}
				
				if (isRegister != 1)
				{
					isRegister = -1;
					printf ("该用户未注册！\n"); 
					userInfo.result = NOT_REGISTER;
				}
				
				writeSize = write(cfd, &userInfo, sizeof(userInfo));
				if (writeSize == -1)
				{
					perror("write");
					return -1;
				}
				
				if (temp == 1 || isRegister != 1)      //被禁言或未注册就退出
				{
					memset(userInfo.name, 0, sizeof(userInfo.name));
					memset(userInfo.toname, 0, sizeof(userInfo.toname));
					memset(userInfo.msg, 0, sizeof(userInfo.msg));
					
					pthread_mutex_unlock(&lock);
					break;
				}
					
				int to_isRegister = -1; 
				// 寻找要发送的用户
				for (i = 0; i < 20; i++)
				{
					if (uMge.flag[i] == 1)
					{
						// 找到了要发送的用户，将其socket保存起来
						if (strcmp(uMge.users[i].name, userInfo.toname) == 0)
						{
							to_isRegister = 1;
							toname_fd = uMge.users[i].socketfd;
							printf ("找到发送对象！\n");
							
							if (uMge.online_flag[i] == 1)      //已登录
							{
								printf ("在线标志位：%d\n", uMge.online_flag[i]);
								printf ("用户%s已登录！\n", uMge.users[i].name);
								
								if(toname_fd != -1)  // 没找到要发送的用户
								{
									
									userInfo.result = FIND_GOAL;   // 找到用户
									
									printf ("%s发送消息给%s : %s\n", userInfo.name, userInfo.toname, userInfo.msg);
									writeSize = write(toname_fd, &userInfo, sizeof(userInfo));
									if (writeSize == -1)
									{
										perror("write");
										return -1;
									}
									
									userInfo.result = SEND_SUCCESS;  // 发送成功
									
									//保存聊天记录
									FILE *file_in = fopen(ch3, "a+");
									if (file_in == NULL)
									{
										perror("fopen TXT");
										return 0;
									}

									fprintf (file_in, "%s", ch1);
									fprintf (file_in, "给");
									fprintf (file_in, "%s", userInfo.toname);
									fprintf (file_in, "发了一条消息：");
									fprintf (file_in, "%s", userInfo.msg);
									fprintf (file_in, "\r\n");
						
									fclose (file_in);
								}
							}
							
							else
							{
								printf ("在线标志位：%d\n", uMge.online_flag[i]);
								printf ("发送对象未登录！\n"); 
								userInfo.result = LOGIN_NULL;
							}
						}
						
					}
				}
				
				if (to_isRegister != 1)
				{
					to_isRegister = -1;
					printf ("发送对象未注册！\n"); 
					userInfo.result = NO_GOAL;
				}
						
				writeSize = write(cfd, &userInfo, sizeof(userInfo));
				if (writeSize == -1)
				{
					perror("write");
					return -1;
				}
				
				memset(userInfo.name, 0, sizeof(userInfo.name));
				memset(userInfo.toname, 0, sizeof(userInfo.toname));
				memset(userInfo.msg, 0, sizeof(userInfo.msg));
				pthread_mutex_unlock(&lock);
				break;
			}
			
			case CHAT_ALL: //群聊
			{
				printf ("收到一条消息\n");
				printf ("用户%s发送了群聊命令:%d\n", userInfo.name,userInfo.cmd);
				
				pthread_mutex_lock(&lock);
				
				//建一个文本文件保存用户聊天记录
				char ch1[10] = {0};
				char ch2[10] = ".txt";
				char ch3[20] = {0};
				
				strcpy (ch1, userInfo.name);
				strcpy (ch3, userInfo.name);
				strcat (ch3, ch2);
				
				int fd_chat = open (ch3, O_RDWR | O_CREAT, S_IRUSR | S_IWUSR);
				if (-1 == fd_chat)
				{
					perror("open TXT");
					return -1;
				}
				
				int i;
				int temp = 0;
				for (i = 0; i < 20; i++)
				{
					//检测该用户是否注册
					if (strcmp(uMge.users[i].name, userInfo.name) == 0)
					{
						isRegister = 1;    
						printf ("该用户已注册！\n"); 
						
						//检测是否被禁言
						if (uMge.ban_flag[i] == 0)
						{
							temp = 0;
							printf ("禁言标志位：%d\n", uMge.ban_flag[i]);
							printf ("该用户允许发言！\n"); 
							
							//检测该用户是否已登录
							if (uMge.online_flag[i] == 1)      //已登录
							{
								printf ("在线标志位：%d\n", uMge.online_flag[i]);
								printf ("用户%s已登录！\n", uMge.users[i].name);
							}
							
							else
							{
								printf ("在线标志位：%d\n", uMge.online_flag[i]);
								printf ("该用户未登录！\n"); 
								userInfo.result = LOGIN_NULL;
							}
						}
						
						else
						{
							temp = 1;
							printf ("禁言标志位：%d\n", uMge.ban_flag[i]);
							printf ("该用户已被禁言！\n"); 
							userInfo.result = BAN_USER;
							
							break;
						}
					}
					
				}
				
				if (isRegister != 1)
				{
					isRegister = -1;
					printf ("该用户未注册！\n"); 
					userInfo.result = NOT_REGISTER ;
				}
				
				writeSize = write(cfd, &userInfo, sizeof(userInfo));
				if (writeSize == -1)
				{
					perror("write");
					return -1;
				}
				
				if (temp == 1 || isRegister != 1)           //被禁言或未注册就退出
				{
					memset(userInfo.name, 0, sizeof(userInfo.name));
					memset(userInfo.msg, 0, sizeof(userInfo.msg));
					pthread_mutex_unlock(&lock);
					break;
				}
				
				//查找所以在线用户
				for (i = 0; i < 20; i++)
				{
					if (strcmp(uMge.users[i].name, userInfo.name) == 0)  //和自己用户名相同就跳过
					{
						continue;
					}
					
					if (uMge.online_flag[i] == 1)      //已登录
					{
						printf ("在线标志位：%d\n", uMge.online_flag[i]);
						printf ("用户%s已登录！\n", uMge.users[i].name);
						toname_fd = uMge.users[i].socketfd;
						printf ("找到发送对象%s！\n", uMge.users[i].name);
						
						if(toname_fd != -1)  // 没找到要发送的用户
						{
							userInfo.result = FIND_GOAL;   // 找到用户
							
							printf ("%s发送消息给%s : %s\n", userInfo.name, uMge.users[i].name, userInfo.msg);
							writeSize = write(toname_fd, &userInfo, sizeof(userInfo));
							if (writeSize == -1)
							{
								perror("write");
								return -1;
							}
							
							//保存聊天记录
							FILE *file_in = fopen(ch3, "a+");
							if (file_in == NULL)
							{
								perror("fopen TXT");
								return 0;
							}

							fprintf (file_in, "%s", ch1);
							fprintf (file_in, "给");
							fprintf (file_in, "%s", uMge.users[i].name);
							fprintf (file_in, "发了一条消息：");
							fprintf (file_in, "%s", userInfo.msg);
							fprintf (file_in, "\r\n");
				
							fclose (file_in);
						}
					}
				}
				
				userInfo.result = SEND_SUCCESS;  // 发送成功
				
				writeSize = write(cfd, &userInfo, sizeof(userInfo));
				if (writeSize == -1)
				{
					perror("write");
					return -1;
				}
				
				memset(userInfo.name, 0, sizeof(userInfo.name));
				memset(userInfo.msg, 0, sizeof(userInfo.msg));
				pthread_mutex_unlock(&lock);
				break;
			}
			
			case ONLINE_USER://查看在线用户
			{
				printf ("收到一条消息\n");
				printf ("用户%s发送了查看在线用户命令:%d\n", userInfo.name,userInfo.cmd);
				
				int i;
				for (i = 0; i < 20; i++)
				{	
					if (uMge.flag[i] == 1)
					{
						if (uMge.online_flag[i] == 1)
						{
							strcpy(userInfo.name, uMge.users[i].name);
							userInfo.result = OLUSER_SUCCESS;
							writeSize = write(cfd, &userInfo, sizeof(userInfo));
							if (writeSize == -1)
							{
								perror("write");
								return -1;
							}
							
						}
					}
				}
				userInfo.result = SEND_END;
				
				writeSize = write(cfd, &userInfo, sizeof(userInfo));
				if (writeSize == -1)
				{
					perror("write");
					return -1;
				}
				
				printf ("数据发送成功！\n");
				memset(userInfo.name, 0, sizeof(userInfo.name));
				break;
			}
			
			case QUIT_LOGIN:  //退出登录
			{
				printf ("收到一条消息\n");
				printf ("用户%s发送了下线命令:%d\n", userInfo.name,userInfo.cmd);
				int i;
				//寻找要退出的用户
				for (i = 0; i < 20; i++)
				{	
					if(strcmp(uMge.users[i].name, userInfo.name) == 0)
					{
						uMge.online_flag[i] = 0;
						printf ("用户%s已下线！\n", uMge.users[i].name);
						userInfo.result = QUIT_SUCCESS;
						
						writeSize = write(cfd, &userInfo, sizeof(userInfo));
						if (writeSize == -1)
						{
							perror("write");
							return -1;
						}
					}
				}
				
				break;
			}
		}
	}
	
}

void Super_User_Interface ()
{    
	system ("clear");
	printf ("********************************\n");
	printf ("~                              ~\n");
	printf ("~                              ~\n");
	printf ("~  1  >>>>>>>>>  查看用户状态  ~\n");
	printf ("~  2  >>>>>>>>>  禁言和解禁    ~\n");
	printf ("~  3  >>>>>>>>>  踢出聊天室    ~\n");
	printf ("~  4  >>>>>>>>>  查看聊天记录  ~\n");
	printf ("~  5  >>>>>>>>>  退出          ~\n");
	printf ("~                              ~\n");
	printf ("********************************\n");
	printf ("                                \n");
	printf ("请选择：");
}

int server_mage(int cfd)
{
	char cho[10];
	char a[10] = "end";
	char b[10] = "login";
	struct user userInfo;
	int writeSize;
	int isRegister = -1;     //用户注册标志位，已注册为1，未注册为-1
	
	strcpy(uMge.Ad_name, ch1);
    strcpy(uMge.Ad_password, ch2); 
	
	while (1)
	{
		scanf ("%s", cho);
		
		if (strcmp(cho, b) == 0)
		{
			char adname[10];
			char adpassword[10];
			
			while (1)
			{
				printf ("用户名：");
				scanf ("%s", adname);
				
				if (strcmp(uMge.Ad_name, adname) != 0)
				{
					printf ("用户名错误！\n");
					continue;
				}
				break;
			}
			
			while (1)
			{
				printf ("密码：");
				scanf ("%s", adpassword);
				
				if (strcmp(uMge.Ad_password, adpassword) != 0)
				{	
					printf ("密码错误！\n");
					continue;
				}
				break;
			}
				
			Super_User_Interface ();
			
			while (1)
			{
				char Function[3]; 
				while (1)
				{
					scanf ("%s", Function);
					if (strlen(Function) != 1)
					{
						printf ("命令错误！请重新输入：");
						continue;
					}
					break;
				}
				switch (Function[0])
				{
					case '1': //查看用户状态
					{
						system ("clear");
						int i;
						for (i = 0; i < 20; i++)
						{
							if (uMge.flag[i] == 1)
							{
								printf ("用户%s\t\t", uMge.users[i].name);
								if (uMge.online_flag[i] == 1)
								{
									printf ("在线\t");
									
									if (uMge.ban_flag[i] == 1)
									{
										printf ("禁言\n");
									}
									
									else
									{
										printf ("\n");
									}
								}
								
								else 
								{
									printf ("离线\t");
									
									if (uMge.ban_flag[i] == 1)
									{
										printf ("禁言\n");
									}
									
									else
									{
										printf ("\n");
									}
								}
							}
						}
						
						printf ("\n");
						
						char ch[3];
						printf ("返回输入1：");
						
						while (1)
						{
							scanf ("%s", ch);
							if(ch[0] != '1')
							{
								printf ("命令错误，请重新输入：");
								continue;
							}
							
							Super_User_Interface ();
							break;
						}
						
						break;
					}
					
					case '2'://禁言和解禁
					{	
						int temp1 = 0;
						while (1)
						{
							system ("clear");
							printf ("***************************\n");
							printf ("~                         ~\n");
							printf ("~  A  >>>>>>>>>  禁言     ~\n");
							printf ("~  B  >>>>>>>>>  解禁     ~\n");
							printf ("~  C  >>>>>>>>>  返回     ~\n");
							printf ("~                         ~\n");
							printf ("***************************\n");
							printf ("                           \n");
							printf ("请选择：");
							
							char cho1[3];
							while (1)
							{ 
								scanf ("%s", cho1);
								if (strlen(cho1) != 1)
								{
									printf ("命令错误！请重新输入：");
									continue;
								}
								break;
							}
							
							switch (cho1[0])
							{
								case 'A'://禁言
								{
									temp1 = 0;
									int toname_fd;
									//打印所有用户状态
									int i;
									for (i = 0; i < 20; i++)
									{
										if (uMge.flag[i] == 1)
										{
											printf ("用户：%s\t\t", uMge.users[i].name);
											if (uMge.online_flag[i] == 1)
											{
												printf ("在线\t");
												
												if (uMge.ban_flag[i] == 1)
												{
													printf ("禁言\n");
												}
												
												else
												{
													printf ("\n");
												}
											}
											
											else 
											{
												printf ("离线\t");
												
												if (uMge.ban_flag[i] == 1)
												{
													printf ("禁言\n");
												}
												
												else
												{
													printf ("\n");
												}
											}
										}
									}
									
									char j_name[20];
									while (1)
									{
										printf ("\n");
										printf ("请选择要禁言的用户：");
										scanf ("%s", j_name);
										
										for (i = 0; i < 20; i++)
										{
											if (strcmp(uMge.users[i].name, j_name) == 0)
											{
												isRegister = 1;
												toname_fd = uMge.users[i].socketfd;
												uMge.ban_flag[i] = 1;    //禁言标志位
												
												printf ("正在更改表中记录.....\n");
												
												int result = sqlite3_open("server.db", &db);
												if (result != SQLITE_OK)
												{
													printf ("open server.db error!\n");
													return -1;
												}
												
												char buff[50];
												char *errmsg;
												sprintf (buff, "update register set ban_flag = 1 where name = '%s'", j_name);
												result = sqlite3_exec(db, buff, NULL, NULL, &errmsg);
												if (result != SQLITE_OK)
												{
													printf ("update register table error : %d(%s)!\n", result, errmsg);
													return -1;
												} 
												printf ("更改成功！\n");
												sqlite3_close(db);
												
												printf ("用户%s已被禁言\n", j_name);
												userInfo.result = BAN_USER;
												
												if (uMge.online_flag[i] == 1)
												{
													writeSize = write(toname_fd, &userInfo, sizeof(userInfo));
													if (writeSize == -1)
													{
														perror("write");
														return -1;
													}
												}
											}
										}
										
										if (isRegister != 1)
										{
											isRegister = -1;
											printf ("该用户未注册！\n");
										}
										
										printf ("继续禁言输入1，返回2：");
										int temp = 0;
										char cho2[3];
										while(1)
										{
											scanf ("%s", cho2);
											if (cho2[0] == '1')
											{
												temp = 0;
												break;
											}
											
											else if (cho2[0] == '2')
											{
												temp = 1;
												break;
											}
											
											else 
											{
												printf ("命令错误！请重新输入：");
											}
											
										}
										
										if (temp != 1)
										{
											continue;
										}
										
										break;
									}
									break;
								}
								
								case 'B':
								{
									temp1 = 0;
									int toname_fd;
									//打印所有用户状态
									int i;
									for (i = 0; i < 20; i++)
									{
										if (uMge.flag[i] == 1)
										{
											printf ("用户：%s\t\t", uMge.users[i].name);
											if (uMge.online_flag[i] == 1)
											{
												printf ("在线\t");
												
												if (uMge.ban_flag[i] == 1)
												{
													printf ("禁言\n");
												}
												
												else
												{
													printf ("\n");
												}
											}
											
											else 
											{
												printf ("离线\t");
												
												if (uMge.ban_flag[i] == 1)
												{
													printf ("禁言\n");
												}
												
												else
												{
													printf ("\n");
												}
											}
										}
									}
									
									char k_name[20];
									while (1)
									{
										printf ("\n");
										printf ("请选择要解禁的用户：");
										scanf ("%s", k_name);
										
										for (i = 0; i < 20; i++)
										{
											if (strcmp(uMge.users[i].name, k_name) == 0)
											{
												isRegister = 1;
												toname_fd = uMge.users[i].socketfd;
												uMge.ban_flag[i] = 0;    //禁言标志位
												
												printf ("正在更改表中记录.....\n");
												
												int result = sqlite3_open("server.db", &db);
												if (result != SQLITE_OK)
												{
													printf ("open server.db error!\n");
													return -1;
												}
												
												char buff[50];
												char *errmsg;
												sprintf (buff, "update register set ban_flag = 0 where name = '%s'", k_name);
												result = sqlite3_exec(db, buff, NULL, NULL, &errmsg);
												if (result != SQLITE_OK)
												{
													printf ("update register table error : %d(%s)!\n", result, errmsg);
													return -1;
												} 
												printf ("更改成功！\n");
												sqlite3_close(db);
												
												printf ("用户%s已被解除禁言\n", k_name);
												userInfo.result = RELIEVE_BAN;
												
												if (uMge.online_flag[i] == 1)
												{
													writeSize = write(toname_fd, &userInfo, sizeof(userInfo));
													if (writeSize == -1)
													{
														perror("write");
														return -1;
													}
												}
											}
										}
										
										if (isRegister != 1)
										{
											isRegister = -1;
											printf ("该用户未注册！\n");
										}
										
										printf ("继续解禁输入1，返回2：");
										int temp = 0;
										char cho2[3];
										while(1)
										{
											scanf ("%s", cho2);
											if (cho2[0] == '1')
											{
												temp = 0;
												break;
											}
											
											else if (cho2[0] == '2')
											{
												temp = 1;
												break;
											}
											
											else 
											{
												printf ("命令错误！请重新输入：");
											}
											
										}
										
										if (temp != 1)
										{
											continue;
										}
										
										break;
									}
									break;
								}
								
								case 'C':
								{
									temp1 = 1;
									Super_User_Interface ();
									break;
								}
								
								default:
								{
									temp1 = 0;
									printf ("命令错误！请重新输入：\n");
									break;
								}
							
							}
							
							if (temp1 != 1)
							{
								continue;
							}
							break;
						}
						break;
					}
					
					case '3'://踢人
					{
						system ("clear");
						char t_name[20];
						int i;
						int toname_fd;
						printf ("用户名：");
						scanf ("%s", t_name);
						for (i = 0; i < 20; i++)
						{
							if (strcmp(uMge.users[i].name, t_name) == 0)
							{
								if (uMge.online_flag[i] == 1)      //已登录
								{
									toname_fd = uMge.users[i].socketfd;
									printf ("在线标志位：%d\n", uMge.online_flag[i]);
									uMge.online_flag[i] = 0;
									printf ("在线标志位：%d\n", uMge.online_flag[i]);
									printf ("用户%s已被踢出聊天室\n", uMge.users[i].name);
									userInfo.result = KICK_USER;
									
									writeSize = write(toname_fd, &userInfo, sizeof(userInfo));
									if (writeSize == -1)
									{
										perror("write");
										return -1;
									}
								}
								
								else 
								{
									printf ("该用户未登录！");
								}
							}
						
						}
						
						printf ("\n");
						
						char ch[3];
						printf ("返回输入1：");
						
						while (1)
						{
							scanf ("%s", ch);
							if(ch[0] != '1')
							{
								printf ("命令错误，请重新输入：");
								continue;
							}
				
							Super_User_Interface ();
							break;
						}
						
						break;
					}
					
					case '4'://查看聊天记录
					{
						system ("clear");
						char ch1[10];
						char ch2[10] = ".txt";
						char ch3[20];
						while (1)
						{
							printf ("请输入查看对象的用户名：");
							scanf ("%s", ch1);
							strcpy (ch3, ch1);
							strcat (ch3, ch2);
							
							FILE *file_in = fopen(ch3, "r");   //以只读方式打开文件         
							if (file_in == NULL)
							{
								perror("fopen TXT");
								printf ("没有该用户的聊天记录！\n");
								continue;
							}
							
							printf ("\n");
							
							char ch;
							while (1)
							{
								ch = fgetc(file_in);
								if (ch == EOF)
								{
									break;
								}
								printf ("%c", ch);
							}
							
							printf ("\n");
							
							int temp = 0;
							printf ("继续查看请输入1，返回输入2：");
							while (1)
							{
								char cho1[3];
								scanf ("%s", cho1);
								if (cho1[0] == '1')
								{
									temp = 0;
									break;
								}
								
								else if (cho1[0] == '2')
								{
									temp = 1;
									Super_User_Interface ();
									break;
								}
								
								else 
								{
									printf ("命令错误！请重新输入：");
								}
							}
							
							if (temp != 1)
							{
								continue;
							}
							
							break;
						}
						
						break;
					}
					
					case '5': //退出
					{
						system ("clear");
						printf ("管理员已下线！\n");
						break;
					}
					
					default:
					{
						printf ("命令错误！请重新输入：");
						break;
					}
				}
				
				if (Function[0] != '5')
				{
					memset(Function, 0, sizeof(Function));
					continue;
				}
				memset(Function, 0, sizeof(Function));
				break;
			}	
		}
		
		
		else if (strcmp(cho, a) == 0)
		{
			system("clear");
			exit(0);
		}
		
		else
		{
			printf ("命令错误！请重新输入：");
		}
	}
}

int main()
{
	int listen_sockfd;
	int ret;
	struct sockaddr_in server_addr;  // 服务器地址结构
	struct sockaddr_in client_addr;  // 客户端的地址
	
	pthread_mutex_init(&lock, NULL);
	
	//创建数据库
	int result = sqlite3_open("server.db", &db);
	if (result != SQLITE_OK)
	{
	    printf ("open server.db error!\n");
		return -1;
	}
    
	char *errmsg;
	result = sqlite3_exec(db, "create table register(name TEXT, password TEXT, flag INTEGER, ban_flag INTEGER, primary key(name))", NULL, NULL, &errmsg);
	if (result != SQLITE_OK && result != 1)
	{
	    printf ("create register table error : %d(%s)!\n", result, errmsg);
		return -1;
	}
	
	sqlite3_close(db);
	
	//读取数据库中数据
	read_userInfo(&uMge);
	
	// 创建监听套接字
	listen_sockfd = socket(AF_INET, SOCK_STREAM, 0);
	if (listen_sockfd == -1)
	{
		perror("create socket error");
		return -1;
	}
	
	// 初始化服务器地址结构
	bzero(&server_addr, sizeof(server_addr));          // 将地址结构变量清零
 	server_addr.sin_family = AF_INET;                  // 选择IPV4地址
	server_addr.sin_addr.s_addr = htonl(INADDR_ANY);   // 监听本地任意IP地址
	server_addr.sin_port = htons(SERV_PORT);           // 将本地端口号转化为网络端口号
	
	// 绑定本地地址和端口号
	ret = bind(listen_sockfd, (struct sockaddr *)&server_addr, sizeof (server_addr));
	if (ret == -1)
	{
		perror ("bind error");
		return -1;
	}

	// 监听套接字
	ret = listen(listen_sockfd, 20);
	if (ret == -1)
	{
		perror("listen error");
		return -1;
	}
	
	
	
	pthread_t tid1;
	// 创建线程处理客户端请求
	int ret1 = pthread_create(&tid1, NULL, (void *)server_mage,  NULL);
	if (ret1 != 0)
	{
		printf ("create pthread1 error!\n");
		return -1;
	}
	pthread_detach(tid1); // 线程分离
	
	while(1)
	{
		int clientfd;
		socklen_t client_len = sizeof(client_addr);
		printf ("等待连接.....\n");
		clientfd = accept(listen_sockfd, (struct sockaddr *)&client_addr, &client_len);
		if (clientfd == -1)
		{
			perror("accept error");
			return -1;
		}			
		
		printf ("the client addr is %s\n", inet_ntoa(client_addr.sin_addr));   //将网络地址转换成“.”点隔的字符串格式，并打印
		
		pthread_t tid;
		// 创建线程处理客户端请求
		int ret = pthread_create(&tid, NULL, (void *)server_request, (void *)clientfd);
		if (ret != 0)
		{
			printf ("create pthread error!\n");
			return -1;
		}
		printf ("创建线程处理客户端请求\n");
		pthread_detach(tid); // 线程分离
	}
	
	pthread_mutex_destroy(&lock);
	//sqlite3_close(db);
	return 0;
}
